<?php

namespace app\shop\controller\user;

use app\common\model\product\Product;
use app\common\model\user\GradeAgent;
use app\common\model\user\GradeProduct;
use app\common\model\user\GradeProductLog;
use app\shop\controller\Controller;
use app\shop\model\user\Grade as GradeModel;
use app\common\model\user\GradeLog as GradeLogModel;

/**
 * 会员等级
 */
class Grade extends Controller
{
    /**
     * 会员等级列表
     */
    public function index()
    {
        $model = new GradeModel;
        $list = $model->getList($this->postData());
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 添加等级
     */
    public function add()
    {
        $model = new GradeModel;
        // 新增记录
        if ($model->add($this->postData())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError('添加失败：' . $model->getError());
    }

    /**
     * 编辑会员等级
     */
    public function edit($grade_id)
    {
        $model = GradeModel::detail($grade_id);
        // 修改记录
        if ($model->edit($this->postData())) {
            return $this->renderSuccess();
        }
        return $this->renderError('添加失败：' . $model->getError());
    }

    /**
     * 删除会员等级
     */
    public function delete($grade_id)
    {
        // 会员等级详情
        $model = GradeModel::detail($grade_id);
        if (!$model->setDelete()) {
            return $this->renderError('已存在用户，删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 会员等级日志
     */
    public function log()
    {
        $model = new GradeLogModel;
        $list = $model->getList($this->postData());
        return $this->renderSuccess('', compact('list'));
    }

    //等级分销奖励
    public function gradeAgent($grade_id)
    {
        $info = GradeAgent::detail($grade_id);
        return $this->renderSuccess('', $info);
    }

    public function saveGradeAgent()
    {
        $data = $this->postData();
        $data['app_id'] = $this->store['app']['app_id'];
        $model = GradeAgent::detail($data['grade_id']);
        if ($model) {
            $model->save($data);
        } else {
            $model = GradeAgent::create($data);
        }
        return $this->renderSuccess('保存成功');
    }

    //等级商品表
    public function gradeProduct($grade_id)
    {
        $model = new Product();
        $ids = GradeProduct::where('grade_id', $grade_id)->column('product_id');
        $lists = $model->getListByIds($ids);
        return $this->renderSuccess('', $lists);
    }

    public function saveGradeProduct()
    {
        $data = $this->postData();
        $data['app_id'] = $this->store['app']['app_id'];
        if(empty($data['grade_id'])){
            return $this->renderError('参数错误');
        }
        $exist_ids = GradeProduct::where('grade_id',$data['grade_id'])->column('product_id');
        $post_ids = $data['product_ids']??[];
        //删除在exist_ids中，不在post_ids中的删除
        $del_ids = array_diff($exist_ids,$post_ids);
        if($del_ids){
            GradeProduct::destroy(function ($query) use ($del_ids) {
                $query->whereIn('product_id', $del_ids);
            });
        }
        //添加在post_ids中，不在exist_ids中的添加
        $add_ids = array_diff($post_ids,$exist_ids);
        if($add_ids){
            foreach ($add_ids as $product_id) {
                GradeProduct::create([
                    'grade_id' => $data['grade_id'],
                    'product_id' => $product_id,
                    'app_id' => $this->store['app']['app_id'],
                ]);
            }
        }
        return $this->renderSuccess('保存成功'); 
    }

    //领取记录
    public function gradeProductLog($grade_id)
    {
        $model = new GradeProductLog();
        $page_size = input('page_size', 10);
        $keyword = input('keyword', '');
        $map = [
            ['grade_id', '=', $grade_id]
        ];
        if ($keyword) {
            $model = $model->hasWhere('user', function ($query) use ($keyword) {
                if (isMobile($keyword)) {
                    $query->where('mobile', $keyword);
                } elseif (is_numeric($keyword)) {
                    $query->where('user_id', $keyword);
                } else {
                    $query->where('nickName|real_name', 'like', '%' . $keyword . '%');
                }
            });
        }
        $list = $model->where($map)->order('id', 'desc')->with(['product', 'user'])->paginate($page_size);
        return $this->renderSuccess('', $list);
    }
}